package edu.nf.llmtest.service.dify;

import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

/**
 * @ Author bin
 * @ Create  2025/10/29 上午10:53
 * dify服务类
 **/
@Service
public class DifyService {
//    @Value("${dify.base-url}")
    private String baseUrl;

//    @Value("${dify.api-key}")
    private String apiKey;

    private static final String CHAT_API = "/chat-messages";

    public String sendMessage(String userId, String conversationId, String query) {
        try {
            JSONObject body = new JSONObject();
            body.put("query", query);
            body.put("user", userId);
            if (conversationId != null) {
                body.put("conversation_id", conversationId);
            }

            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(baseUrl + CHAT_API))
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer " + apiKey)
                    .POST(HttpRequest.BodyPublishers.ofString(body.toString()))
                    .build();

            HttpClient client = HttpClient.newHttpClient();
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

            return response.body();
        } catch (Exception e) {
            e.printStackTrace();
            return "请求失败：" + e.getMessage();
        }
    }
}